package com.grantheath.erebus.model 
{
	import com.grantheath.erebus.model.enum.notifications.ErebusInitializationNotifications;
	import com.grantheath.erebus.model.enum.names.ErebusProxyNames;
	import com.grantheath.erebus.model.interfaces.IErebusClassReferenceProxy;

	import flash.display.DisplayObjectContainer;
	import flash.events.IOErrorEvent;
	import flash.events.Event;
	import flash.net.URLRequest;
	import flash.net.URLLoader;
	import flash.utils.getDefinitionByName;

	import com.grantheath.erebus.model.interfaces.IErebusLayersProxy;

	/**
	 * @author grantheath
	 */
	public class ErebusXMLLayersProxy extends ErebusLayersProxy implements IErebusLayersProxy 
	{
		protected var xmlSrc : String;

		public function ErebusXMLLayersProxy()
		{
			var layerXMLLoader : URLLoader = new URLLoader();
			var classReferenceProxy : IErebusClassReferenceProxy;
			
			super();
			classReferenceProxy = facade.retrieveProxy(ErebusProxyNames.CLASS_REFERENCE_PROXY) as IErebusClassReferenceProxy;
			appStage = classReferenceProxy.appStage;
			if(!xmlSrc) {
				xmlSrc = "XML/Layers.xml";
			}
			layerXMLLoader.addEventListener(Event.COMPLETE, onXMLLoad);
			layerXMLLoader.addEventListener(IOErrorEvent.IO_ERROR, onXMLLoadError);
			layerXMLLoader.load(new URLRequest(xmlSrc));
		}

		private function layersFromXML(data : XML) : void
		{
			var xmlLayers : XMLList = data.layer;
			
			for(var i : int = (xmlLayers.length() - 1); i > -1; i--) {
				var classReferenceProxy : IErebusClassReferenceProxy = facade.retrieveProxy(ErebusProxyNames.CLASS_REFERENCE_PROXY) as IErebusClassReferenceProxy;
				var layerClass : Class = classReferenceProxy.layerClasses[0];
				var xmlLayer : XML = xmlLayers[i];
				var layer : DisplayObjectContainer;
				
				if(String(xmlLayer.@layerType)) {
					try {
						layerClass = getDefinitionByName(String(xmlLayer.@pageNode)) as Class;
					} catch(error : Error) {
						//TODO better undefined pageNodeClass error
						throw new Error("undefined layer class: " + String(xmlLayer.@pageNode));
					}
				}
				layer = new layerClass();
				if(String(xmlLayer.@id)) {
					addLayerById(xmlLayer.@id, layer);
				}
				if(String(xmlLayer.@default)) {
					defaultLayer = layer;
				}
				if(String(xmlLayer.@preloaderDefault)) {
					defaultPreloaderLayer = layer;
				}
			}
		}

		//EVENT HANDLERS
		private function onXMLLoad(event : Event) : void
		{
			var loader : URLLoader = event.target as URLLoader;
			var layersXML : XML = new XML(loader.data);
			
			layersFromXML(layersXML);
			sendNotification(ErebusInitializationNotifications.INITIALIZE_PROXIES);
		}

		private function onXMLLoadError(event : IOErrorEvent) : void
		{
			//TODO better XML load error
			throw new Error("Can't load load layers XML from URL: " + xmlSrc);
		}
	}
}
